package com.three.box.network

import android.content.Intent
import com.hjq.toast.Toaster
import com.tencent.mmkv.MMKV
import com.three.box.R
import com.three.box.activity.LoginActivity
import com.three.box.base.BoxApp
import com.three.box.config.Constant
import okhttp3.Interceptor
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.StandardCharsets

class TokenInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        // try the request
        val originalResponse = chain.proceed(request)

        /**通过如下的办法曲线取到请求完成的数据
         *
         * 原本想通过  originalResponse.body().string()
         * 去取到请求完成的数据,但是一直报错,不知道是okhttp的bug还是操作不当
         *
         * 然后去看了okhttp的源码,找到了这个曲线方法,取到请求完成的数据后,根据特定的判断条件去判断token过期
         */
        val responseBody = originalResponse.body()!!
        val source = responseBody.source()
        source.request(Long.MAX_VALUE) // Buffer the entire body.
        val buffer = source.buffer()
        var charset = UTF8
        val contentType = responseBody.contentType()
        if (contentType != null) {
            charset = contentType.charset(UTF8)
        }
        assert(charset != null)
        val bodyString = buffer.clone().readString(charset)

        val errno = JSONObject(bodyString)["errno"]

        if (errno == 501){ // 根据和服务端的约定判断token过期
            // go to login
            MMKV.defaultMMKV().remove(Constant.TOKEN)
            MMKV.defaultMMKV().remove(Constant.LOGIN_RESULT)
            Toaster.show(R.string.login_expired)
            val intent = Intent(BoxApp.instance(), LoginActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            BoxApp.instance().startActivity(intent)
        }

        // otherwise just pass the original response on
        return originalResponse
    }

    companion object {
        private val UTF8 = StandardCharsets.UTF_8
    }
}
